// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import { BezierData } from "./Bezier/BezierData";
import { fishManager } from "./FishManager";
import { colliderObjManager } from "./NewQuadtree/ColliderObjManager";

const { ccclass, property } = cc._decorator;

@ccclass
export default class FishCtr extends cc.Component {

    id: number = null;
    // LIFE-CYCLE CALLBACKS:
    lastPosition: any = null

    bezierData: BezierData = null;
    // onLoad () {}

    start() {

    }

    /**
     * 回收时 进行恢复初始化
     */
    unuse() {
        this.bezierData = null;
        this.node.stopAllActions()
        this.id = null;
    }

    /**
     * 取出来时 
     */
    reuse() {

    }

    /**
     * 
     * @param points 鱼的路径
     * @param time 鱼的整体运动时间
     * @param id 鱼的id
     */
    initFish(points: [any], time:number,id:number) {
        this.bezierData = new BezierData()
        this.enabled = true;
        this.id = id
        this.node.on('touchend', this.click, this);

        this.spawnFish(points, time);

    }

    spawnFish(points: [any], time) {

        let self = this

        let action, bezier1, actionLists

        //先设置鱼的位置在起始点
        this.node.setPosition(points[0])

        let cutArray = new Array<cc.Vec2[]>();
        let model = 0
        points.length > 2 ? model = 2 : model = 1
        switch (model) {
            case 1://直线
                action = cc.moveTo(time, points[points.length - 1].x, points[points.length - 1].y)
                break;
            case 2://曲线
                bezier1 = points
                if (points.length >= 3 && points.length % 2 == 1) {
                    var num = (bezier1.length - 3) / 2 + 1
                    if ((num - Math.floor(num)) != 0) {
                        console.log('鱼的路线错误 1')
                        return
                    }
                    for (var i = 0; i < num; i++) {
                        var bar: cc.Vec2[] = [cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0)]
                        cutArray[i] = bar
                    }

                    for (var i = num - 1; i >= 0; i--) {
                        var c2 = bezier1.pop()
                        var c1 = bezier1.pop()
                        var c0 = bezier1[bezier1.length - 1]

                        cutArray[i][2] = cc.v2(Math.floor(c2.x), Math.floor(c2.y))
                        cutArray[i][1] = cc.v2(Math.floor(c1.x), Math.floor(c1.y))
                        cutArray[i][0] = cc.v2(Math.floor(c0.x), Math.floor(c0.y))
                        // //console.log('转化  ', cutArray[i])
                    }
                } else {
                    console.log('出现了 曲线不对得鱼')

                }

                break;
            default:
                break;
        }

        this.lastPosition = points[0];


        if (model == 1) {// 走直线的鱼 同步情况下 要自己算出来 他当前的点的坐标
            var finish = cc.callFunc(function () {

                self.node.stopAllActions()
                try {
                    //删除 鱼的碰撞检测
                    colliderObjManager.romoveFishCollider(self.id)
                    fishManager.putFish(self.node)
                } catch (error) {

                }

            }, this, this.node);

            this.node.runAction(cc.sequence(action, finish));
            return
        }

        //this.node.runAction(self.action);
        for (let index = 0; index < cutArray.length; index++) {
            const element = cutArray[index];
            this.bezierData.addBezierCurve(element)
        }

        this.bezierData.setBezierCurveRunTime(time)
        this.bezierData.setPointCount(35)
        this.bezierData.saveBezierPath()
        actionLists = this.computeBezierActions()

        this.node.runAction(cc.sequence(actionLists));
    }

    computeBezierActions(): any[] {
        let self = this
        let bezierCurveData = this.bezierData.getBezierCurveData();
        let actionLists = [];

        // 创建动作队列
        for (var i = 0, len = bezierCurveData.points.length; i < len; i++) {
            const point = bezierCurveData.points[i];
            //计算当前路段需要的时间
            let time = point.length / bezierCurveData.length * bezierCurveData.time;
            point.time = time;
            // 创建动作
            let action = cc.moveTo(time, cc.v2(point.x, point.y));
            actionLists.push(action);

        }
        actionLists.push(cc.callFunc(() => {
            //删除 鱼的碰撞检测 把鱼存到
            colliderObjManager.romoveFishCollider(self.id)
            fishManager.putFish(self.node)
        }))
        return actionLists
    }

    click() {

    }

    update(dt) {
        let currentPos = this.node.getPosition();

        // 如果位移不超过1，不改变角度
        if (!this.lastPosition) {
            console.log('难道说')
            return
        }

        if (currentPos.sub(this.lastPosition).mag() < 2) {
            return;
        }

        // 计算角度
        let degree = null;

        if (currentPos.x - this.lastPosition.x == 0) {
            // 垂直
            if (currentPos.y - this.lastPosition.y > 0) {
                degree = 90;
            } else {
                degree = -90;
            }
        } else {

            if (currentPos.x > this.lastPosition.x) {
                degree = Math.atan((currentPos.y - this.lastPosition.y) / (currentPos.x - this.lastPosition.x)) * 180 / 3.14;
            } else {
                degree = Math.atan((currentPos.y - this.lastPosition.y) / (currentPos.x - this.lastPosition.x)) * 180 / 3.14 -180;
            }
        }
        this.node.angle = degree
        this.lastPosition = currentPos;

    }
}
